package org.spider.api.utils.flow;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.spider.api.domain.utilDomain.KeyValue;
import org.spider.api.domain.utilDomain.SpiderNode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class SpiderFlowUtils {

    /**
     * 转换成图有两种方式，一种是邻接表存储，给出一个起点就可以运行<br>
     * 另一种是链表存储
     *
     * @param json
     * @return
     */
    public static SpiderNode loadJsonFromString(String json) {
        final JSONObject jsonObject = JSON.parseObject(json);
        JSONArray nodeList = (JSONArray) jsonObject.get("nodeList");
        JSONArray lineList = (JSONArray) jsonObject.get("lineList");
        SpiderNode root = null;
        Map<String, SpiderNode> nodeMap = new HashMap<>();
        //获取node的基本属性和配置属性
        for (int i = 0; i < nodeList.size(); i++) {
            //每一个node都是一个jsonObject 存了节点的名称，注释，几何和配置信息
            JSONObject elem = (JSONObject) nodeList.get(i);
            SpiderNode node = new SpiderNode();
            node.setNodeId(elem.getString("id"));
            node.setShape(elem.getString("style"));
            JSONObject config = elem.getJSONObject("config");
            String nodeName = config.getString("nodeName");
            node.setNodeName(nodeName);
            node.setJsonProperty(elem.getJSONObject("config"));
            String style = elem.getString("style");
            if ("start".equals(style)) {
                root = node;
            }
            nodeMap.put(node.getNodeId(), node);
        }
        //获取line的基本属性
        for (int i = 0; i < lineList.size(); i++) {
            JSONObject line = (JSONObject) lineList.get(i);
            //加载节点的连线关系
            final String source = line.getString("source");
            final String target = line.getString("target");
            SpiderNode sourceNode = nodeMap.get(source);
            SpiderNode targetNode = nodeMap.get(target);
            sourceNode.getNextNodes().add(targetNode);
            String condition = line.getString("condition");
            if (StringUtils.isBlank(condition)) {
                sourceNode.getCondition().put(targetNode.getNodeId(), "true");
            }
            else {
                sourceNode.getCondition().put(targetNode.getNodeId(), line.getString("condition"));
            }
        }
        return root;
    }


    /**
     * 没化简的json数据会有大量的空格和换行符，甚至比本身数据都多，因此写个简单函数来化简一下
     * @param json
     * @return
     */
    public static String simpleJson(String json){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < json.length(); i++) {
            char ch = json.charAt(i);
            if(ch!=' ' && ch != '\n') {
                char res = ch == '\'' ? '\"' : ch;
                sb.append(res);
            }
        }
        return sb.toString();
    }

    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    public static void main(String[] args) {
        String json = "{\"comments\":\"type属性暂时不用,多余了\",\"data\":{\"lineList\":[{\"condition\":\"\",\"geomProperty\":{\"common\":{}},\"source\":\"0\",\"target\":\"1\"},{\"condition\":\"\",\"geomProperty\":{\"common\":{}},\"source\":\"1\",\"target\":\"2\"},{\"condition\":\"\",\"geomProperty\":{\"common\":{}},\"source\":\"2\",\"target\":\"3\"}],\"nodeList\":[{\"parent\":\"1\",\"name\":\"开始\",\"style\":\"start\",\"id\":\"0\",\"type\":\"node\"},{\"geomProperty\":{\"x\":20,\"y\":20},\"name\":\"完美世界爬虫\",\"style\":\"request\",\"id\":\"1\",\"type\":\"node\",\"config\":{\"tls-validate\":\"1\",\"method\":\"GET\",\"shape\":\"request\",\"response-charset\":\"\",\"request-body\":\"\",\"retryCount\":\"\",\"body-type\":\"none\",\"timeout\":\"\",\"url\":\"http://127.0.0.1:8050\",\"repeat-enable\":\"0\",\"sleep\":\"3000\",\"proxy\":\"\",\"loopVariableName\":\"i\",\"loopCount\":\"10\",\"body-content-type\":\"text/plain\",\"follow-redirect\":\"1\",\"retryInterval\":\"\",\"value\":\"开始抓取\",\"cookie-auto-set\":\"1\"}},{\"geomProperty\":{\"x\":200,\"y\":200},\"name\":\"定义变量\",\"style\":\"variable\",\"id\":\"2\",\"type\":\"node\",\"config\":{\"var-value\":[\"${resp.html}\",\"${json.parse(jsonC)}\"],\"loopCount\":\"expression\",\"loopName\":\"name-1\",\"var-name\":[\"jsonC\",\"content\"]}},{\"parent\":\"1\",\"vertex\":\"1\",\"geomProperty\":{\"x\":\"410\",\"width\":\"32\",\"y\":\"70\",\"height\":\"32\"},\"style\":\"output\",\"id\":\"3\",\"value\":\"输出\",\"config\":{\"shape\":\"output\",\"csvEncoding\":\"GBK\",\"tableName\":\"\",\"output-name\":[\"内容\"],\"loopVariableName\":\"\",\"output-value\":[\"${content.data}\"],\"output-database\":\"0\",\"loopCount\":\"\",\"output-all\":\"0\",\"datasourceId\":\"1\",\"csvName\":\"\",\"output-csv\":\"0\",\"value\":\"输出\"}}]},\"name\":\"完美世界\"}";
        System.out.println(json);
        SpiderNode root = loadJsonFromString(json);
        System.out.println(root);
        SpiderNode node = root;
        while (node.getNextNodes().size()>0){
            node = node.getNextNodes().get(0);
            List<KeyValue> listByKeys = node.getDictListByKey("variable");
            System.out.println(listByKeys);
            System.out.println(node);
        }
        System.out.println(node.getNextNodes().get(0).getNextNodes());
    }
}

//        System.out.println(jsonObject);
//        //与任务运行无关
//        System.out.println(jsonObject.get("name"));
//        System.out.println(jsonObject.get("comments"));
//        // other
//        System.out.println(data);
//        System.out.println(nodeList);
//        System.out.println(o);